package com.dizner.androidcarclient;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements SocketClient.OnMessageListener, CompoundButton.OnCheckedChangeListener, LongPressButton.LongTouchListener, SeekBar.OnSeekBarChangeListener, SuperDiverButton.LongTouchListener {

    @BindView(R.id.iv_connect_status)
    ImageView ivConnectStatus;
    @BindView(R.id.btn_forward)
    LongPressButton btnForward;
    @BindView(R.id.btn_left)
    LongPressButton btnLeft;
    @BindView(R.id.btn_right)
    LongPressButton btnRight;
    @BindView(R.id.btn_back)
    LongPressButton btnBack;
    @BindView(R.id.btn_re_connect)
    Button btnReConnect;
    @BindView(R.id.btn_re_scan)
    Button btnScan;
    @BindView(R.id.btn_super)
    SuperDiverButton btnSuper;

    private static final String TAG = "MainActivity";
    @BindView(R.id.btn_enable_engine)
    Switch btnEnableEngine;
    @BindView(R.id.btn_engine_left)
    Switch btnEngineLeft;
    @BindView(R.id.vb_engine_left_power)
    VerticalSeekBar vbEngineLeftPower;
    @BindView(R.id.sc_servo)
    SeekBar scServo;
    @BindView(R.id.tv_speed)
    TextView tvSpeed;

    private boolean isConnected;
    private int def_miles = 50;//默认间隔时间
    private String targetIp = "192.168.0.11";
    private int targetPort = 10201;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
//        SocketClient.getInstance().startClient(targetIp, targetPort);
        SocketClient.getInstance().register(this);
        initView();
    }

    private void initView() {

        btnEnableEngine.setOnCheckedChangeListener(this);
        btnEngineLeft.setOnCheckedChangeListener(this);

        btnForward.setOnLongTouchListener(this, def_miles);
        btnBack.setOnLongTouchListener(this, def_miles);
        btnLeft.setOnLongTouchListener(this, def_miles);
        btnRight.setOnLongTouchListener(this, def_miles);
        btnSuper.setOnLongTouchListener(this, def_miles);

        vbEngineLeftPower.setMax(100);
        vbEngineLeftPower.setOnSeekBarChangeListener(this);
        scServo.setOnSeekBarChangeListener(this);
    }

    @Override
    public void onMessage(BaseMessage msg) {
        Log.i(TAG, msg.toString());
        if (msg.getMsgType() == SocketClient.Msg_Type.MSG_CHARACTER) {
            Log.i(TAG, msg.getMsgBody());
        } else if (msg.getMsgType() == SocketClient.Msg_Type.MSG_SYSTEM) {
            String temp = msg.getMsgBody();
            temp = temp.replaceAll("[-]", "");
            char one = temp.charAt(0);
            char two = temp.charAt(1);
            char three = temp.charAt(2);
            char four = temp.charAt(3);

            int oneInt = Integer.parseInt(String.valueOf(one));
            int twothreeInt = Integer.parseInt(String.valueOf(two) + String.valueOf(three) + String.valueOf(four));

            btnEngineLeft.setChecked(oneInt == 1);
            Log.i(TAG, "引擎速度：" + twothreeInt);
            tvSpeed.setText(String.format("当前车速：%s", twothreeInt));
//            vbEngineLeftPower.setProgress(twothreeInt);

        }
    }

    @Override
    public void onScanResult(final String targetIp) {
        DialogUtils.getInstance().showMsgDialog(this, String.format("扫描到IP地址为%s的小车，是否连接？", targetIp), new DialogUtils.OnConfirmDialogClickListener() {
            @Override
            public void onOKBtnClick(DialogInterface dialog) {
                MainActivity.this.targetIp = targetIp;
//                SocketClient.getInstance().close();
                SocketClient.getInstance().startClient(targetIp, targetPort);
            }

            @Override
            public void onCancelBtnClick(DialogInterface dialog) {

            }
        });
    }

    @Override
    public void onConnect() {
        ivConnectStatus.setImageResource(R.drawable.icon_connected);
//        btnReConnect.setText("断开");
        btnReConnect.setVisibility(View.GONE);
        btnScan.setVisibility(View.GONE);
        isConnected = true;
        SocketClient.getInstance().sendMsg("{'type':2,'body':'HELLO'}");
    }

    @Override
    public void onDisconnect() {
        ivConnectStatus.setImageResource(R.drawable.icon_connect_fail);
//        btnReConnect.setText("连接");
        isConnected = false;
        initViewStatus();
    }

    private void initViewStatus() {
        btnReConnect.setVisibility(View.VISIBLE);
        btnScan.setVisibility(View.VISIBLE);
        btnEngineLeft.setChecked(false);
    }

    public void send(View view) {
        SocketClient.getInstance().sendMsg("{'type':2,'body':'HELLO'}");
    }

    @OnClick({R.id.btn_re_connect, R.id.btn_re_scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_re_connect:
                if (isConnected) {
                    SocketClient.getInstance().close();
                } else {
                    SocketClient.getInstance().startClient(targetIp, targetPort);
                }
                break;
            case R.id.btn_re_scan:
                SocketClient.getInstance().scanCarServer();
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.btn_enable_engine://启动/停止-自动模式
                if (isChecked) {
                    SocketClient.getInstance().sendMsg(new ControlMessage(04, "AUTO_START").toString());
//                    AutoPlayManager.getInstance(this).run();
                } else {
                    SocketClient.getInstance().sendMsg(new ControlMessage(04, "AUTO_STOP").toString());
//                    AutoPlayManager.getInstance(this).stop();
                }
                break;
            case R.id.btn_engine_left://引擎
                if (isChecked) {
                    SocketClient.getInstance().sendMsg(new ControlMessage(04, "LEFT_START").toString());
                } else {
                    SocketClient.getInstance().sendMsg(new ControlMessage(04, "LEFT_STOP").toString());
                }
                break;
        }
    }

    @Override
    public void onTouchStart(View view) {

    }

    @Override
    public void onTouchEnd(View view) {
        switch (view.getId()) {
            case R.id.btn_forward:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "FORWARD_END").toString());
                break;
            case R.id.btn_back:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "BACK_END").toString());
                break;
            case R.id.btn_left:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "LEFT_END").toString());
                break;
            case R.id.btn_right:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "RIGHT_END").toString());
                break;
        }
    }

    @Override
    public void onLongTouch(View view) {
        switch (view.getId()) {
            case R.id.btn_forward:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "FORWARD").toString());
                break;
            case R.id.btn_back:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "BACK").toString());
                break;
            case R.id.btn_left:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "LEFT").toString());
                break;
            case R.id.btn_right:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "RIGHT").toString());
                break;
            case R.id.btn_stop:
                SocketClient.getInstance().sendMsg(new ControlMessage(04, "STOP").toString());
                break;
        }
    }


    @Override
    public void onLeftTouch(View view, int progress, double angle) {
        SocketClient.getInstance().sendMsg(new ControlMessage(01, "LEFT").toString());
    }

    @Override
    public void onTopTouch(View view, int progress, double angle) {
        SocketClient.getInstance().sendMsg(new ControlMessage(01, "FORWARD").toString());
    }

    @Override
    public void onRightTouch(View view, int progress, double angle) {
        SocketClient.getInstance().sendMsg(new ControlMessage(01, "RIGHT").toString());
    }

    @Override
    public void onBottomTouch(View view, int progress, double angle) {
        SocketClient.getInstance().sendMsg(new ControlMessage(01, "BACK").toString());
    }

    @Override
    public void onStopTouch(View view) {
        SocketClient.getInstance().sendMsg(new ControlMessage(04, "STOP").toString());
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.vb_engine_left_power:
                Log.i(TAG, "引擎1速度：" + progress);
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "SPEED" + progress).toString());
                tvSpeed.setText(String.format("当前车速：%s", progress));
                break;
            case R.id.sc_servo:
                SocketClient.getInstance().sendMsg(new ControlMessage(01, "SERVO" + progress).toString());
//                tvSpeed.setText(String.format("当前舵机：%s", progress));
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
